package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.Md5Util;
import com.cskaoyan.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SystemManagementServiceImpl implements SystemManagementService {
    @Autowired
    RoleMapper roleMapper;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    LogMapper logMapper;

    @Autowired
    StorageMapper storageMapper;

    @Autowired
    PermissionMapper permissionMapper;

    /**
     * options
     *
     * @return
     */
    @Override
    public List<RoleVO> selectRole() {
        List<RoleVO> roleVOS = roleMapper.selectRole();
        return roleVOS;
    }

    /**
     * 管理员列表
     *
     * @return
     */
    @Override
    public AdminVO query(AdminBO adminBO) {
        //分页
        //页码，数据量
        PageHelper.startPage(adminBO.getPage(), adminBO.getLimit());

        AdminExample adminExample = new AdminExample();
        //排序
        adminExample.setOrderByClause(adminBO.getSort() + " " + adminBO.getOrder());
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andDeletedNotEqualTo(true);
        if (Objects.nonNull(adminBO.getUsername())) {
            criteria.andUsernameLike("%" + adminBO.getUsername() + "%");
        }
        List<Admin> admins = adminMapper.selectByExample(adminExample);

        //total
        //满足条件的所有数据量
        //pageinfo获得分页信息
        PageInfo<Admin> feedbackPageInfo = new PageInfo<>(admins);//查询结果放进来
        long total = feedbackPageInfo.getTotal();//总的数据量

        AdminVO adminVO = new AdminVO();
        adminVO.setItems(admins);
        adminVO.setTotal(total);
        return adminVO;
    }

    /**
     * 添加管理员
     *
     * @param admin
     */
    @Override
    public Admin addAdmin(Admin admin) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.format(date);
        admin.setAddTime(date);

        admin.setDeleted(false);

        String username = admin.getUsername();
        Integer count = adminMapper.check(username);
        if (count == 0) {
            try {
                String md5Password = Md5Util.getMd5(admin.getPassword());
                admin.setPassword(md5Password);
                adminMapper.insertSelective(admin);
                Admin admin1 = adminMapper.selectByPrimaryKey(admin.getId());
                return admin1;
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 删除管理员
     *
     * @param admin
     */
    @Override
    public void deleteAdmin(Admin admin) {
        admin.setDeleted(true);
        adminMapper.updateByPrimaryKeySelective(admin);
    }

    /**
     * 管理员跟新
     *
     * @param admin
     */
    @Override
    public void updateAdmin(Admin admin) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.format(date);
        admin.setUpdateTime(date);
        adminMapper.updateByPrimaryKeySelective(admin);
    }

    /**
     * 操作日志列表
     *
     * @return
     */
    @Override
    public LogVO queryLog(LogBO logBO) {
        //分页
        //页码，数据量
        PageHelper.startPage(logBO.getPage(), logBO.getLimit());

        LogExample logExample = new LogExample();
        //排序
        logExample.setOrderByClause(logBO.getSort() + " " + logBO.getOrder());
        LogExample.Criteria criteria = logExample.createCriteria();
        criteria.andDeletedNotEqualTo(true);
        if (Objects.nonNull(logBO.getName())) {
            criteria.andAdminLike("%" + logBO.getName() + "%");
        }
        List<Log> logs = logMapper.selectByExample(logExample);

        //total
        //满足条件的所有数据量
        //pageinfo获得分页信息
        PageInfo<Log> feedbackPageInfo = new PageInfo<>(logs);//查询结果放进来
        long total = feedbackPageInfo.getTotal();//总的数据量

        LogVO logVO = new LogVO();
        logVO.setItems(logs);
        logVO.setTotal(total);
        return logVO;
    }

    @Override
    public RoleGetVO getRole(RoleBO roleBO) {
        PageHelper.startPage(roleBO.getPage(), roleBO.getLimit());

        RoleExample roleExample = new RoleExample();
        roleExample.setOrderByClause(roleBO.getSort() + " " + roleBO.getOrder());
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andDeletedNotEqualTo(true);
        if (Objects.nonNull(roleBO.getName())) {
            criteria.andNameLike("%" + roleBO.getName() + "%");
        }

        List<Role> roles = roleMapper.selectByExample(roleExample);

        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        long total = pageInfo.getTotal();

        RoleGetVO roleGetVO = new RoleGetVO();
        roleGetVO.setTotal(total);
        roleGetVO.setItems(roles);
        return roleGetVO;
    }

    @Transactional
    @Override
    public RoleCreateVO createRole(Map roleMap) {
        Date addTime = new Date();
        Role role = new Role();
        role.setAddTime(addTime);
        role.setDeleted(false);
        role.setDesc((String) roleMap.get("desc"));
        role.setName((String) roleMap.get("name"));
        roleMapper.insertSelective(role);

        RoleCreateVO roleCreateVO = new RoleCreateVO();
        roleCreateVO.setId(role.getId());
        roleCreateVO.setName((String) roleMap.get("name"));
        roleCreateVO.setAddTime(addTime);
        roleCreateVO.setUpdateTime(addTime);

        return roleCreateVO;
    }

    @Transactional
    @Override
    public void updateRole(Role role, String op) {
        if ("delete".equals(op)) {
            role.setDeleted(true);
        }
        Date updateTime = new Date();
        role.setUpdateTime(updateTime);
        roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public StorageVOGet getStorageList(StorageBO storageBO) {
        PageHelper.startPage(storageBO.getPage(), storageBO.getLimit());

        StorageExample storageExample = new StorageExample();
        storageExample.setOrderByClause(storageBO.getSort() + " " + storageBO.getOrder());
        StorageExample.Criteria criteria = storageExample.createCriteria();
        criteria.andDeletedNotEqualTo(true);
        if (Objects.nonNull(storageBO.getName())) {
            criteria.andNameLike("%" + storageBO.getName() + "%");
        }
        if (Objects.nonNull(storageBO.getKey())) {
            criteria.andKeyLike("%" + storageBO.getKey() + "%");
        }


        List<Storage> storages = storageMapper.selectByExample(storageExample);

        PageInfo<Storage> pageInfo = new PageInfo<>(storages);
        long total = pageInfo.getTotal();

        StorageVOGet storageVOGet = new StorageVOGet();
        storageVOGet.setTotal(total);
        storageVOGet.setItems(storages);
        return storageVOGet;
    }

    @Transactional
    @Override
    public void updateStorage(Storage storage, String op) {
        if ("delete".equals(op)) {
            storage.setDeleted(true);
        }
        Date updateTime = new Date();
        storage.setUpdateTime(updateTime);
        storageMapper.updateByPrimaryKeySelective(storage);
    }


    @Override
    public PermissionsVO getPermissions(int roleId) {

        PermissionsVO permissionsVO = new PermissionsVO();
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria permissionExampleCriteria = permissionExample.createCriteria();
        permissionExampleCriteria.andRoleIdEqualTo(roleId);
        permissionExampleCriteria.andDeletedEqualTo(false);
        List<Permission> permissionList = permissionMapper.selectByExample(permissionExample);
        List<String> permissions = permissionList.stream().map(Permission::getPermission).collect(Collectors.toList());

        permissionsVO.setAssignedPermissions(permissions);

        List<PermissionCategoryL1> allPermission = permissionMapper.getAllPermission();

        permissionsVO.setSystemPermissions(allPermission);

        if (permissions.contains("*")) {
            List<String> perms = allPermission.stream()
                    .flatMap(p1 -> p1.getChildren().stream())
                    .flatMap(p2 -> p2.getChildren().stream())
                    .map(PermissionCategoryL1.PermissionDetail::getId)
                    .collect(Collectors.toList());
            permissionsVO.setAssignedPermissions(perms);

        }

        return permissionsVO;
    }

    @Transactional
    @Override
    public int updatePermisssions(PermissionsBO permissionsBO) {

        Permission permission = new Permission();
        permission.setDeleted(true);
        permission.setUpdateTime(new Date());

        PermissionExample example = new PermissionExample();
        PermissionExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(permissionsBO.getRoleId());
        permissionMapper.updateByExampleSelective(permission, example);

        return permissionMapper.upsert(permissionsBO);
    }
}
